package com.hmdp.utils;


import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Stack;

/**
 * 全局唯一 ID 生成器
 * @author benxin
 */
@Component
public class IDWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 2025-01-01的时间戳
     */
    private static final Long BEGIN_TIMESTAMP = 1735660800L;

    /**
     * 序列号位数
     */
    private static final Long COUNT_BITS = 32L;

    public Long nextId(String keyPrefix) {
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowEpochSecond = now.toEpochSecond(ZoneOffset.of("+8"));
        long timeStamp = nowEpochSecond - BEGIN_TIMESTAMP;
        // 生成订单序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyMMdd"));
        // 每日的订单数
        Long increment = stringRedisTemplate.opsForValue().increment("incr:" + keyPrefix + ":" + date);
        // 拼接并返回
        return timeStamp << COUNT_BITS | increment;
    }

//    public static void main(String[] args) {
//        // 计算2025-01-01的时间戳
//        LocalDateTime time = LocalDateTime.of(2025, 1, 1, 0, 0);
//        // 设置时区为东8区
//        ZoneOffset offset = ZoneOffset.of("+8");
//        // 转化为纪元秒
//        long epochSecond = time.toEpochSecond(offset);
//        System.out.println(epochSecond);
//    }
}
